package top.bingoz.wanandroid.data.http.transformer

import com.trello.rxlifecycle2.LifecycleTransformer
import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.reactivestreams.Publisher
import top.bingoz.wanandroid.bean.BaseResult
import top.bingoz.wanandroid.common.utils.DeviceUtils

/**
 * @author su
 * @date 2018/7/30
 * @description
 */
class DataTransformer<T>() : FlowableTransformer<BaseResult<T>, T>, ObservableTransformer<BaseResult<T>, T> {

    private var lifecycle: LifecycleTransformer<T>? = null

    constructor(lifecycle: LifecycleTransformer<T>?) : this() {
        this.lifecycle = lifecycle
    }

    override fun apply(upstream: Flowable<BaseResult<T>>): Publisher<T> {
        val observable = upstream.doOnSubscribe {
            if (DeviceUtils.isWifiProxy()) {
                it.cancel()
            }
        }
                .flatMap { result ->
                    if (result.errorCode >= 0) {

                        Flowable.defer {
                            Flowable.just(result.data!!)
                        }


                    } else {
                        Flowable.error<T>(Exception(result.errorMsg))
                    }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())


        if (lifecycle != null) {
            return observable.compose(lifecycle!!)
        }

        return observable

    }

    override fun apply(upstream: Observable<BaseResult<T>>): ObservableSource<T> {
        val observable = upstream.doOnSubscribe {
            if (DeviceUtils.isWifiProxy()) {
                it.dispose()
            }
        }
                .flatMap { result ->
                    if (result.errorCode >= 0) {
                        Observable.just(result.data!!)
                    } else {
                        Observable.error<T>(Exception(result.errorMsg))
                    }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())


        if (lifecycle != null) {
            return observable.compose(lifecycle!!)
        }

        return observable
    }

}